package com.lib.core.base

import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.text.TextUtils
import android.view.Window
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.viewbinding.ViewBinding
import com.lib.core.R

/**
 * Dialog基类
 */
abstract class BaseDialog<out V : ViewBinding> : Dialog {



    protected val binding: V by lazy { getViewBinding() }

    constructor(context: Context) : this(context, R.style.baseDialog)
    constructor(context: Context, themeResId: Int) : super(context, themeResId)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        val window = this.window
        getDialogWindows(window)
        if (window != null) {
            val windowManager = window.windowManager
            val display = windowManager.defaultDisplay
            val p = window.attributes
            p.width = (display.width * dialogWith).toInt()
            window.attributes = p
        }
        initView()
    }


    /**
     * 获取Window
     *
     * @param window
     */
   open protected fun getDialogWindows(window: Window?) {}

    /**
     * 初始化view
     */
    protected abstract fun initView()

    protected abstract fun getViewBinding(): V

    /**
     * dialog宽度
     *
     * @return 若布局中定义宽度，默认写1.0f
     */
    protected val dialogWith: Float
        protected get() = 1f

    protected fun checkTextNull(editText: EditText, hint: String?): Boolean {
        if (TextUtils.isEmpty(getText(editText))) {
            Toast.makeText(context, hint, Toast.LENGTH_SHORT).show()
            return true
        }
        return false
    }

    fun getText(editText: TextView): String {
        val text = editText.text.toString().trim { it <= ' ' }
        return if (TextUtils.isEmpty(text)) "" else text
    }
}